#!/bin/bash
###
# @Author: admin@attacker.club
# @Date: 2022-10-22 17:06:16
# @LastEditTime: 2023-08-23 22:04:51
# @Description:
###
#  rm /scripts/disk_clean.sh -f; mkdir /scripts ; wget -P /scripts http://wuyou.run/scripts/repair/disk_clean.sh ;chmod 750 /scripts/disk_clean.sh
# */5 * * * * /scripts/disk_clean.sh

# 清理磁盘空间
function clean() {
    year=$(date '+%Y')

    if [ $year ] >1; then
        echo "ok"
    else
        echo "error"
        year=2
    fi
    echo $year

    echo "开始清理磁盘空间"
    journalctl --vacuum-size=50M

    find /var/log/ -name "*.log*" -mtime +0 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    find /var/log/ -name "*$year*" -mtime +0 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    find /tmp -name "*$year*" -mtime +0 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1

    if [ -d /data ]; then
        find /data -name "*$year*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    fi
    if [ -d /usr/share/ ]; then
        find /usr/share/ -name "*$year*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    fi
    if [ -d /var/log/ ]; then
        find /var/log/ -name "*$year*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    fi

    if [ -f /var/spool/mail/root ]; then
        echo >/var/spool/mail/root
    fi
    if [ -f /var/log/messages ]; then
        echo >/var/log/messages
        rm /var/log/*20* -f
    fi

}

# 判断磁盘使用率>80%
num=$(df -h | awk -F"[ %]+" '/[0-9]/  { if ($5>=80) print $5,$6}' | wc -l)
if [ $num != 0 ]; then
    clean
else
    echo "磁盘空闲"
fi
